#include "friendmassager.h"
#include "ui_friendmassager.h"
#include "friendorgroupinformwidget.h"
#include "someItem/frienditem.h"

#include "Core/messagedispatcher.h"

#include "Core/tcpclient.h"

#include <QDebug>
FriendMassager::FriendMassager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FriendMassager)
{
    ui->setupUi(this);
    InitForUi();
    InitHandler();
    linkTcpServiceSignalAndSlot();
}

FriendMassager::~FriendMassager()
{
    delete ui;
}

void FriendMassager::InitForUi()
{
    ui->FriendTree->setHeaderHidden(true);

    ui->GroupTree->setHeaderHidden(true);

    ui->FriendTree->clear();
}

void FriendMassager::InitHandler()
{
    QTreeWidgetItem *Friend=new QTreeWidgetItem(ui->FriendTree);
    Friend->setText(0,"朋友");

    FriendDivideHandler[FRIEND_FREIND]=Friend;


    QTreeWidgetItem *Parent=new QTreeWidgetItem(ui->FriendTree);
    Parent->setText(0,"家人");
    FriendDivideHandler[FRIEND_PARENT]=Parent;
}

void FriendMassager::linkTcpServiceSignalAndSlot()
{
    connect(MessageDispatcher::GetInstance()->getFriendServer(),
            &FriendService::GlobalNoticeAddFriendStatus,
            this,&FriendMassager::ActNoticeAddFriendSlot);

    connect(this,&FriendMassager::Sig_PullFriendList,
            TcpClient::get_instance(),&TcpClient::SendMsg);

    connect(MessageDispatcher::GetInstance()->getFriendServer(),
            &FriendService::EmitFriendList,
            this,&FriendMassager::ActFriendListRespond);
}


void FriendMassager::SetFriendItem(QString HeadPic,QString Name,QString Sign,int Status,int Div)
{
    QTreeWidgetItem *GetTypeItem=FriendDivideHandler[Div];
    QTreeWidgetItem *item=new QTreeWidgetItem(GetTypeItem);
    FriendItem* itemWidget = new FriendItem();
    itemWidget->Set(HeadPic,Name,Sign,Status,Div);
    ui->FriendTree->setItemWidget(item,0,itemWidget);
}
void FriendMassager::on_FriendInformBtn_clicked()
{
    (new FriendOrGroupInformWidget(MSG_TYPE_FRIEND_INFORM_PULL_REQUEST))->show();
}

void FriendMassager::ActNoticeAddFriendSlot(QJsonObject INFO)
{
    //好友列表因添加好友而发生变化
}

void FriendMassager::on_FlashFriendBtn_clicked()
{
    ReSetFriendTree();
    QJsonObject Body;
    Body["USER"]=TcpClient::get_instance()->getUserName();
    emit Sig_PullFriendList(MSG_TYPE_PULL_FRIEND_LIST_REQUEST,Body);
}

void FriendMassager::ActFriendListRespond(QJsonObject body)
{
    QJsonArray LIST=body["LIST"].toArray();
    for(int i=0;i<LIST.size();i++){
        QJsonObject oFriend=LIST[i].toObject();
        SetFriendItem(oFriend["HEADPIC"].toString(),oFriend["FID"].toString(),"",
                oFriend["STATUS"].toInt(),oFriend["RELATE"].toInt());
    }

}

void FriendMassager::ReSetFriendTree()
{
    FriendDivideHandler.clear();
    ui->FriendTree->clear();
    InitHandler();

}
